package com.honghu.villagepost.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.honghu.villagepost.R;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Copyright (c) 2018 Miguan Inc All rights reserved.
 * Created by Liaopeikun on 2018/2/2
 */
public abstract class BaseDialog extends DialogFragment {

    private static final String TAG = BaseDialog.class.getSimpleName();
    private Unbinder mBind;

    @SuppressLint("RestrictedApi")
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.customDialog);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(getLayoutRes(), null);
        builder.setView(view, 0, 0, 0, 0);
        AlertDialog alertDialog = builder.create();
        mBind = ButterKnife.bind(this, view);
        initView(view);
        return alertDialog;
    }

    protected abstract int getLayoutRes();

    protected abstract void initView(View view);

    public boolean isShowing() {
        if (getDialog() != null && getDialog().isShowing()) {
            return true;
        }
        return false;
    }

    public void showDialog(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(this, BaseDialog.class.getSimpleName());
        ft.commitAllowingStateLoss();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBind.unbind();
    }

}
